package com.nowcoder.community.actuator;

import com.nowcoder.community.util.GenerateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

//注意，这些 actuator 路径应该只能管理员访问
//自定义actuator的端口
@Component
// /actuator/database 进行访问
@Endpoint(id = "database")  //端口的id，便于我们访问
public class DatabaseEndpoint {

    private static final Logger logger = LoggerFactory.getLogger(DatabaseEndpoint.class);

    @Autowired
    private DataSource dataSource;

    //这个是 Get 请求访问的，WriteOperation 才是Post
    //说明这个 端口端点，只能通过 get 请求访问
    @ReadOperation
    public String checkConnection() {
        try (
                Connection conn = dataSource.getConnection();
        ) {
            return GenerateUtil.getJsonString(0, "获取连接成功!");
        } catch (SQLException e) {
            logger.error("获取连接失败:" + e.getMessage());
            return GenerateUtil.getJsonString(1, "获取连接失败!");
        }
    }

}
